package com.atguigu.day22.tcpsocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Scanner;

public class Server2 {
    public static void main(String[] args) {
        System.out.println("-----------Server2--------------");
        //1.创建服务端对象
        try (ServerSocket serverSocket = new ServerSocket(9999)) {

            while (true){
                //2.获取连接的客户端socket
                Socket socket = serverSocket.accept();
                //3.将Socket传递到线程内
                new SocketThread(socket).start();
            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
class SocketThread extends Thread{
   private Socket socket;

    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //1.获取输入流
        try (Scanner sc = new Scanner( socket.getInputStream());
             //2.获取输出流
             PrintStream ps = new PrintStream(socket.getOutputStream());

        ) {
            //接收数据
            String message = sc.nextLine();
            //数据反转
            StringBuilder reverse = new StringBuilder(message).reverse();

            System.out.println(socket.getInetAddress()+","+ LocalDateTime.now()+",发来的信息是:"+message+",反转后:"+reverse);
            //将数据反馈到客户端
            ps.println(reverse.toString());


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
